Add delete_node functionality for linked list #11599
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Describe your change:
This PR introduces a new function to handle the deletion of a node in a singly linked list when given access to only that specific node, not the head.
Changes include:
A delete() method added to the Node class that:
Copies the data from the next node into the current node.
Bypasses the next node to effectively "delete" the current node.
Raises an exception if the current node is the tail, since deleting the tail with this method is not possible.
Added custom CannotDeleteTailError exception for handling cases where the deletion is attempted on the tail node.
Motivation:
The problem of deleting a node from a singly linked list when only the reference to that node is provided is a common interview problem and a useful addition to this repository's linked list algorithms. This solution avoids traversal from the head node and directly modifies the node itself by manipulating pointers and data.
Added some sample test cases as well.
Checklist: